package com.framework.core.utils;


import android.util.Log;

import com.framework.core.bean.RestError;
import com.framework.core.exception.AppException;
import com.framework.core.exception.NetworkErrorException;
import com.framework.core.exception.NetworkTimeOutException;
import com.framework.core.exception.ServerBusyException;
import com.framework.core.exception.SystemException;

import retrofit2.adapter.rxjava.HttpException;

public class ExceptionUtil {
    private static final String TAG = "Exception";
    public static final int SUCCESS = 200;
    public static final int EXCEPTION_TICK_OUT = 500;
    public static final int EXCEPTION_BASE = 500;
    public static final int EXCEPTION_VALIDITY = EXCEPTION_BASE + 1;
    //网络异常
    public static final int EXCEPTION_NETWORK = EXCEPTION_BASE + 2;
    //数据异常(脏数据)
    public static final int EXCEPTION_DIRTY_DATA = EXCEPTION_BASE + 3;
    //业务异常
    public static final int EXCEPTION_BUSINESS = EXCEPTION_BASE + 4;

    //app异常
    public static final int EXCEPTION_APP = EXCEPTION_BASE + 5;
    //app异常
    public static final int EXCEPTION_SYSTEM = EXCEPTION_BASE + 6;

    public static RestError generateRestError(Throwable throwable) {
        if (null == throwable) return new RestError("未知错误!");

        String message = throwable.getMessage();
        String errCode = "";
        final int type;

        if (throwable instanceof NetworkTimeOutException
                || throwable instanceof NetworkErrorException
                || throwable instanceof ServerBusyException) {
            type = EXCEPTION_NETWORK;
        } else if (throwable instanceof AppException) {
            AppException appException = (AppException) throwable;
            errCode = appException.getErrCode();
            type = EXCEPTION_APP;
        } else if (throwable instanceof SystemException) {
            SystemException systemException = (SystemException) throwable;
            errCode = systemException.getErrCode();
            type = EXCEPTION_SYSTEM;
        } else if (throwable instanceof HttpException) {
            HttpException httpException = (HttpException) throwable;
            int code = httpException.code();
            if (code == 401) {
                message = "登录失效，请重新登录";
            }
            type = EXCEPTION_SYSTEM;
        } else {
            type = EXCEPTION_BUSINESS;
            message = "未知错误";
        }
        if (message == null) {
            message = "";
        }
        Log.e(TAG, message);

        RestError restError = new RestError(message);
        restError.setErrCode(errCode);
        restError.setErrorType(type);
        return restError;
    }
}
